package com.px.auth.security;

import com.px.auth.config.ApiSecurityConfig;
import com.px.auth.util.TokenUtil;
import com.px.common.core.RespCode;
import com.px.common.core.Response;
import com.px.common.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import static com.px.common.security.AuthConst.REDIS_TOKEN_EXPIRE;

@Slf4j
@Service
public class AjaxLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void onLogoutSuccess(
            HttpServletRequest request,
            HttpServletResponse response,
            Authentication authentication)
            throws IOException {
        String token = request.getHeader(ApiSecurityConfig.HEADER);
        if (token == null){
            writeResponse(response);
            return;
        }
        try {
            Map claims = TokenUtil.getClaims(token);
            String userId = (String) claims.get("userid");

            Set<String> overdue =
                    redisTemplate.opsForZSet().rangeByScore(REDIS_TOKEN_EXPIRE, 0, new Date().getTime() / 1000);
            if (overdue != null)
                overdue.forEach(s -> redisTemplate.opsForZSet().remove(REDIS_TOKEN_EXPIRE, s));
            redisTemplate.opsForZSet().add(REDIS_TOKEN_EXPIRE, userId, new Date().getTime() / 1000);
        } catch (Exception e) {
            log.info("logout token error: " + RespCode.TOKEN_ERROR);
//            throw new RespException(RespCode.TOKEN_ERROR, null);
        }
        writeResponse(response);
    }

    public void writeResponse(HttpServletResponse response) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().println(JsonUtil.toJson(Response.success(null)));
        response.getWriter().flush();
    }
}
